package cn.walls1717.juc.interrupt;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 中断标志相关的坑
 *
 * @author walls1717
 * @create 2022/12/10 14:28
 **/
@Slf4j
public class Interrupt3Demo {

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    log.info("中断标志 -> true，程序停止");
                    break;
                }

                /*
                线程处于sleep，join，wait等状态下，被调用了interrupt方法，那么将会抛出异常，
                并将中断标志设置为false。因此这里会出现无限循环bug，需要在抛出异常时，重新将
                中断标志设置为true。
                 */
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }

                log.info("hello...");
            }
        }, "t1");
        t1.start();

        TimeUnit.SECONDS.sleep(1);

        t1.interrupt();
        log.info("t1中断标志 -> {}", t1.isInterrupted());

    }
}
